<?php
/**
 * @copyright	Copyright (C) 2010 Michael Richey. All rights reserved.
 * @license		GNU General Public License version 3; see LICENSE.txt
 */
// no direct access
defined('_JEXEC') or die;
jimport('joomla.plugin.plugin');
jimport('joomla.language.language');
jimport('joomla.language.helper');
class plgSystemDetectLanguage extends JPlugin
{
	function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config);
	}

	function onAfterInitialise()
	{
		$mainframe = &JFactory::getApplication();
		$client = JFactory::getApplication()->isAdmin()?array('admin','admin_language'):array('site','language');
		$user = &JFactory::getUser();
		$config =& JFactory::getConfig();
		$language = $config->getValue('config.language');
		/*$slang = &JFactory::getLanguage();
		$langx = $slang->get('_lang');		*/
		$hasDetectLang = JRequest::getVar('saveLang','',"COOKIE");
		$url = JRequest::getURI();		
		if(!$hasDetectLang)
		{
			$browserlanguage = JLanguageHelper::detectLanguage();	
			$arrLangs = array();
			$arrLangs[] = 'vi-VN';
			$arrLangs[] = 'en-GB';
			if(!in_array($browserlanguage,$arrLangs))
				return;
			
			$user->setParam( 'language', $browserlanguage );
			setcookie ("saveLang", $browserlanguage, time() + 30*24*60*60);
			if($hasDetectLang !=$browserlanguage)
			{
				$itemid=$_REQUEST['Itemid'];
				$quoPos=strPos($url,'?');
				$nowPage=substr($url,0,$quoPos);
				$nURL=$nowPage.'?Itemid='.$itemid;
				$nURL=JRoute::_($nURL);
				$mainframe->redirect($nURL);
				$mainframe->close();
				/*return;
				if(strpos($url,"?"))
					$mainframe->redirect($url."&setLang=".$browserlanguage);
				else
					$mainframe->redirect($url."?setLang=".$browserlanguage);*/
			}
		}
		
	}
	function onAfterRoute(){
		global $mainframe;
		$user = &JFactory::getUser();
		$option = JRequest::getVar("option");
		$setLang = JRequest::getVar("setLang",'');
		if($setLang)
			return;
		
		$url = JRequest::getURI();
		$config =& JFactory::getConfig();
		$language = $config->getValue('config.language');
		
		$menu = &$mainframe->getMenu();
		if($menu)
			$activeMenu = &$menu->getActive();
		
		if(!is_null($activeMenu)&&$option =="com_content")
		{
			$menuParams= $menu->getParams($activeMenu->id);
			$lang = $menuParams->get('lang');
			if(!empty($lang)&&$lang!= $language)
			{
				$config->setValue('config.language',$lang);
				$doc = &JFactory::getLanguage();
				$doc->setLanguage($lang);			
				setcookie ("saveLang", $lang, time() + 30*24*60*60);
				$user->setParam( 'language', $lang );
				
				/*if(strpos($url,"?"))
					$mainframe->redirect($url."&setLang=".$lang);
				else
					$mainframe->redirect($url."?setLang=".$lang); */
			}
		}
		
	}
}
